package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet("/xiazai")
public class xiazai extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name1 = request.getParameter("name");
        String name = new String(name1.getBytes("iso-8859-1"),"utf-8");
        String mimeType = getServletContext().getMimeType(name);
        response.setContentType(mimeType);
        //更改此头可以让用户下载的内容名字与之前一致
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(name,"utf-8"));

       InputStream in = getServletContext().getResourceAsStream( name);
        ServletOutputStream out = response.getOutputStream();
        int len=0;
        byte[] arr = new byte[1024];
        while((len=in.read(arr))!=-1){
            out.write(arr,0,len);
        }
    }
    }

